/**
 * @author banglong
 * @date 2016/8/23.
 */
define(['avalon', 'Layer', 'text!../html/index/bill/newBillTemp.html!strip', 'newBillApi',
    'Condition', 'Conditions', 'tools', 'GoodsSelectDialog', 'depsSelectDialog', 'batchDialog', 'batchInfoDialog',
    'getApiConfig', 'getVmConfig', 'CommonBill', 'Ygsq',
    'text!../html/index/bill/comNewBillTable.html!strip', 'text!../html/index/bill/viewBillTable.html!strip', 'text!../html/index/bill/packageBillTable.html!strip',
    'text!../html/index/bill/comNewBillForm.html!strip', 'text!../html/index/bill/packageBillForm.html!strip',
    'text!../html/index/bill/disinfectBillForm.html!strip', 'text!../html/index/bill/disinfectBillTable.html!strip',
    'text!../html/index/bill/applyBillForm.html!strip', 'text!../html/index/bill/applyBillTable.html!strip', 'buildBillInfo', 'bus', 'AccountQuery','laydate'
  ],
  function (avalon, layer, htmlTemp, api, Condition, Conditions, tools, GoodsSelectDialog, depsSelectDialog, batchDialog, batchInfoDialog,
    getApiConfig, getVmConfig, CommonBill, Ygsq, comNewBillTable, viewNewBillTable, packageBillTable,
    comNewBillForm, packageBillForm, disinfectBillForm, disinfectBillTable,
    applyBillForm, applyBillTable, buildBillInfo, bus, AccountQuery) {

    return function () {
      var self = this;
      var runtimeParam;
      var ygsq$main;
      var ygsqParam;
      var getRuntimeParam = function () {
        return {
          refreshBillListTable: false, //初始化 刷新list false
          limitGoodsBookArr: ['000000000000CC', '000000000000TT', '000000000000WW', '000000000000ZZ'],
          timeObj: {}
        };
      };

      var newBillVm;
      var getVmOption = function () {
        return {
          $id: 'addNewBill',
          breadcrumb: '', //路径
          BillStatus: '', // 单据状态 新建 查改 修改
          BillType: '',
          isGYKS: false,
          isChange: false,

          columnNames: [], // 表格列名
          columnValueNames: [], // 表格值

          InDeptName: '', //入库科室
          InDeptAccountID: '', //入库科室
          InDeptAccountCode: '', //入库科室

          OutDeptName: '', //出库科室
          OutDeptAccountID: '', //出库科室
          OutDeptAccountCode: '', //出库科室

          inputGoodsName: '', //物品搜索名
          InDeptNameDisabled: true, // 出库科室可选
          OutDeptNameDisabled: true, // 入库科室可选

          Comment: '', //备注
          StatusStr: '', //状态
          chooseGoods: [],
          bill: new CommonBill(),
          // 是否可以保存 避免多条数据的误操作
          canSave: true,

          // 返回操作
          back: function () {
            var main = document.querySelector('#main');
            main.removeChild(tools.getFirstElementChild(main));
            main.appendChild(documentNodeTree[0]); // 添加内容 billList 界面
            if (runtimeParam.refreshBillListTable) {
              bus.triggerHandler('billlist.refreshBillsTable'); // 刷新表格
            }
            self.destroy();
          },
          // 改变参考价格
          handleApplyCountInput: function (event) {
            var target = event.target ? event.target : event.srcElement;
            var index = parseInt(target.parentNode.getAttribute('data_index'));
            if (!(/^[0-9]*$/.test(target.value))) {
              return;
            }
            var count = parseInt(newBillVm.chooseGoods[index].ApplyNum) * parseFloat(newBillVm.chooseGoods[index].RefPrice);
            if (isNaN(count)) {
              count = 0;
            }
            newBillVm.chooseGoods[index].consultMoney = count.toFixed(3);
          },
          // 处理申请数的 失去焦点的操作
          handleApplyCountBlur: function (event) {
            var target = event.target ? event.target : event.srcElement;
            var index = parseInt(target.parentNode.getAttribute('data_index'));
            if (!(/^[0-9]*$/.test(target.value)) || target.value === '') {
              newBillVm.chooseGoods[index].ApplyNum = 0;
              newBillVm.chooseGoods[index].consultMoney = 0;
            }
          },
          // 删除商品
          deleteGoods: function (index) { // 删除商品
            if (confirm("是否要删除这个物品申请记录？")) {
              newBillVm.chooseGoods.splice(index, 1);
            }
          },
          // 选择物品
          showGoodsSelectDialog: function (event, index) {
            tools.throttle(runtimeParam.timeObj, function () {
              var searchValue = newBillVm.inputGoodsName;
              // 当 index 不为空的时候 searchValue 为输入框输入的 只
              if (typeof index === 'number') {
                searchValue = newBillVm.chooseGoods[index].GoodsCode;
              }
              newBillVm.inputGoodsName = '';

              new GoodsSelectDialog().init({
                Openparm: runtimeParam.Openparm,
                isGYKS: JSON.parse(JSON.stringify(newBillVm.isGYKS)),
                CurrentDeptAccount: runtimeParam.CurrentDeptAccount,
                ProviderDeptAccount: runtimeParam.OutDeptAccount,
                OutDeptAccountID: newBillVm.OutDeptAccountID,
                searchValue: searchValue, //初始的查询信息
                BillType: runtimeParam.BillType,
                pushChooseGoods: function (data) { // 选择物品

                  // 监测是否保存了 重复的物品
                  var chooseIndex = -1;
                  var filter = newBillVm.chooseGoods.filter(function (entry, i) {
                    if (data.GoodsCode === entry.GoodsCode) {
                      chooseIndex = i;
                      return entry;
                    }
                  });
                  // 申请单可以放两个相同的物品
                  if (filter.length > 0 && runtimeParam.BillType !== 'sq') {
                    // 此处避免修改时选择了相同的物品的提示
                    if (chooseIndex !== index) {
                      tools.handleError('请不要重复选择物品');
                    }
                  }
                  // 如果 index 有值的话 替换
                  else {
                    // 保存 code 用于失去焦点的时候的判断
                    // 包类 需要判断 packageid
                    if (data.PackageCode &&
                      (newBillVm.BillType === 'dh' || newBillVm.BillType === 'jy')) {
                      data.oldPackageCode = data.PackageCode
                    } else {
                      data.oldGoodsCode = data.GoodsCode;
                    }
                    if (typeof index === 'number') {
                      // set 方法 可以 改变值
                      var arr = newBillVm.chooseGoods.$model;
                      arr[index] = data;
                      newBillVm.chooseGoods = arr;
                    } else {
                      newBillVm.chooseGoods.push(data);
                    }
                  }
                  handlerEnter(event);
                }
              });
            });
          },
          // 失去焦点的时候 判断 物品代码 是否合格
          editingBlur: function (index) {
            var data = newBillVm.chooseGoods[index];
            if (data.oldGoodsCode) {
              if (data.GoodsCode !== data.oldGoodsCode) {
                data.GoodsCode = data.oldGoodsCode;
              }
            } else {
              if (data.PackageCode !== data.oldPackageCode) {
                data.PackageCode = data.oldPackageCode;
              }
            }

          },
          // 保存单据
//      saveBill: function () { // 保存 单据
//        	  
//              newBillVm.canSave = false;
//              var result = checkApplyCount(runtimeParam.BillType);
//              if (!result) {
//                  newBillVm.canSave = true;
//                  return;
//              }
//              if (runtimeParam.limitGoodsBookArr.indexOf(runtimeParam.Openparm.GoodsBook) !== -1) {
//            	  var totalSum = 0;
//                  for (var i = 0; i < newBillVm.chooseGoods.length; i++) {
//                      var data = newBillVm.chooseGoods[i];
//                      totalSum += Number(data.$model.consultMoney) //总金额
//                  }
//                  getDepBalance(function(balance){
//                      if(balance){
//                           if (!newBillVm.isGYKS) {
//                                      var requestCounter = 0; // 检测物品规格次数 当该次数和物品次数相同的时候 能够继续执行
//                                      var flag = false; // 标记是否需要继续检测 一旦出现错误的申请规格 则停止执行
//                                      newBillVm.chooseGoods.forEach(function (good) {
//                                          if (!flag) {
//                                              api.getBoxSpec({
//                                                  className: 'BoxSpecManager',
//                                                  method: 'GetBoxSpec',
//                                                  condition: JSON.stringify(new Condition('bzgg.GoodsID', null, 'Equal', good.GoodsID, "String"))
//                                              }).then(function (jsonResult) {
//                                                  if (jsonResult.issuccess !== 0) {
//                                                      return Promise.reject('查询物品规格信息失败');
//                                                  }
//
//                                                  var result = JSON.parse(jsonResult.result);
//                                                  var errorSpec = [];
//                                                  for (var i = 0; i < result.length; i++) {
//                                                      var data = result[i];
//                                                      if ((parseInt(good.ApplyNum) / data.BoxSpec) % 1 !== 0) {
//                                                          errorSpec.push(data.BoxSpec)
//                                                      }
//                                                  }
//                                                  if (errorSpec.length === result.length && result.length !== 0) {
//                                                      return Promise.reject('申请的' + good.GoodsName + '数量与该物品的规格数量不符！规格为:' + errorSpec.join(','));
//                                                  }
//                                                  requestCounter++;
//                                                  if (requestCounter === newBillVm.chooseGoods.length) {
//                                                      saveBillByBillType(runtimeParam, newBillVm);
//                                                  }
//
//                                              })['catch'](function (ex) {
//                                                  newBillVm.canSave = true;
//                                                  tools.handleError(ex);
//                                              });
//                                          }
//                                      });
//                                  } else {
//                                      saveBillByBillType(runtimeParam, newBillVm);
//                                  }
//                      }else return false;
//
//                  })
//              }else{
//            	  if (!newBillVm.isGYKS) {
//                      var requestCounter = 0; // 检测物品规格次数 当该次数和物品次数相同的时候 能够继续执行
//                      var flag = false; // 标记是否需要继续检测 一旦出现错误的申请规格 则停止执行
//                      newBillVm.chooseGoods.forEach(function (good) {
//                        if (!flag) {
//                          api.getBoxSpec({
//                            className: 'BoxSpecManager',
//                            method: 'GetBoxSpec',
//                            condition: JSON.stringify(new Condition('bzgg.GoodsID', null, 'Equal', good.GoodsID, "String"))
//                          }).then(function (jsonResult) {
//
//                            if (jsonResult.issuccess !== 0) {
//                              return Promise.reject('查询物品规格信息失败');
//                            }
//
//                            var result = JSON.parse(jsonResult.result);
//                            var errorSpec = [];
//                            for (var i = 0; i < result.length; i++) {
//                              var data = result[i];
//                              if ((parseInt(good.ApplyNum) / data.BoxSpec) % 1 !== 0) {
//                                errorSpec.push(data.BoxSpec)
//                              }
//                            }
//                            if (errorSpec.length === result.length && result.length !== 0) {
//                              return Promise.reject('申请的' + good.GoodsName + '数量与该物品的规格数量不符！规格为:' + errorSpec.join(','));
//                            }
//                            requestCounter++;
//                            if (requestCounter === newBillVm.chooseGoods.length) {
//                              saveBillByBillType(runtimeParam, newBillVm);
//                            }
//
//                          })['catch'](function (ex) {
//                            newBillVm.canSave = true;
//                            tools.handleError(ex);
//                          });
//                        }
//                      });
//                    } else {
//                      saveBillByBillType(runtimeParam, newBillVm);
//                    }
//              }
//              
//              
//          },
 saveBill: function () { // 保存 单据
        	  
              newBillVm.canSave = false;
              var result = checkApplyCount(runtimeParam.BillType);
              if (!result) {
                  newBillVm.canSave = true;
                  return;
              }
            	  if (!newBillVm.isGYKS) {
                      var requestCounter = 0; // 检测物品规格次数 当该次数和物品次数相同的时候 能够继续执行
                      var flag = false; // 标记是否需要继续检测 一旦出现错误的申请规格 则停止执行
                      newBillVm.chooseGoods.forEach(function (good) {
                        if (!flag) {
                          api.getBoxSpec({
                            className: 'BoxSpecManager',
                            method: 'GetBoxSpec',
                            condition: JSON.stringify(new Condition('bzgg.GoodsID', null, 'Equal', good.GoodsID, "String"))
                          }).then(function (jsonResult) {

                            if (jsonResult.issuccess !== 0) {
                              return Promise.reject('查询物品规格信息失败');
                            }

                            var result = JSON.parse(jsonResult.result);
                            var errorSpec = [];
                            for (var i = 0; i < result.length; i++) {
                              var data = result[i];
                              if ((parseInt(good.ApplyNum) / data.BoxSpec) % 1 !== 0) {
                                errorSpec.push(data.BoxSpec)
                              }
                            }
                            if (errorSpec.length === result.length && result.length !== 0) {
                              return Promise.reject('申请的' + good.GoodsName + '数量与该物品的规格数量不符！规格为:' + errorSpec.join(','));
                            }
                            requestCounter++;
                            if (requestCounter === newBillVm.chooseGoods.length) {
                              saveBillByBillType(runtimeParam, newBillVm);
                            }

                          })['catch'](function (ex) {
                            newBillVm.canSave = true;
                            tools.handleError(ex);
                          });
                        }
                      });
                    } else {
                      saveBillByBillType(runtimeParam, newBillVm);
                    }
            
              
              
          },
          // 修改 单据 的状态
          changeStatus: function () {
            newBillVm.isChange = !newBillVm.isChange;
          },
          // 提交申请
          saveBillAndApply: function () {
            var result = checkApplyCount(runtimeParam.BillType);
            if (!result) return;
          /*  var falg=true;
            layer.alert('是否跳入阳光采购申请单', {
      		  title:"信息",
      		  closeBtn: 0  // 是否显示关闭按钮
      		  ,btn: ['确认','取消'] //按钮
      		  ,icon: 6  // icon
      		  ,yes:function(){
      			falg=false;
      		    //layer.msg('确认')
      		    //login(param,loginDept);
      			layer.closeAll('dialog'); 
      			$(".new-bill").empty();
      		    ygsqParam.breadcrumb="阳光采购申请单-申请单管理";
      		  //ygsqParam.runtimePara.breadcrumb="阳光采购申请单-申请单管理";

      		    console.info(ygsqParam);
      		    // var ygsq$main=$('#main');
      		  new Ygsq().init($('#main'), ygsqParam);
      		  },btn2:function(){
      		//	 layer.msg('取消')
            runtimeParam.refreshBillListTable = true;
           if (runtimeParam.bill && runtimeParam.BillStatus !== 'new' && sendAndNullifyBill) { // 发送
             var obj = getApiConfig.buildNewBillRequestParam(newBillVm.isGYKS, true, runtimeParam.BillStatus, runtimeParam.BillType);
             sendAndNullifyBill(runtimeParam.bill, obj);
               }
      		  }});*/
            
            
            runtimeParam.refreshBillListTable = true;
            if (runtimeParam.bill && runtimeParam.BillStatus !== 'new' && sendAndNullifyBill) { // 发送
              var obj = getApiConfig.buildNewBillRequestParam(newBillVm.isGYKS, true, runtimeParam.BillStatus, runtimeParam.BillType);
             
              sendAndNullifyBill(runtimeParam.bill, obj);
                }
          },
          // 选择科室
          chooseDesp: function (e, type) {
            tools.throttle(runtimeParam.timeObj, function () {
              // 科室选择框
              var deps = JSON.parse(localStorage.getItem('deps'));
              var searchValue = type === 'rk' ? newBillVm.InDeptName : newBillVm.OutDeptName;
              depsSelectDialog.init(deps, function (dep) {
                if (type === 'rk') {
                  newBillVm.InDeptName = dep.Ksmc;
                  newBillVm.InDeptAccountID = dep.DeptAccountID;
                  newBillVm.InDeptAccountCode = dep.Ksdm;
                } else if (type === 'ck') {
                  newBillVm.OutDeptName = dep.Ksmc;
                  newBillVm.InDeptAccountID = dep.DeptAccountID;
                  newBillVm.OutDeptAccountCode = dep.Ksdm;
                }
              }, searchValue);
            })
          },
          // 查看批次信息
          getBatchInfo: function (index) {
            if (newBillVm.isChange) {
              return;
            }
            if (runtimeParam.BillType !== 'jh' && runtimeParam.BillType !== 'zy') {
              return;
            }
            var good = JSON.parse(JSON.stringify(newBillVm.chooseGoods[index]));
            batchInfoDialog.init({
              good: good,
              api: api,
              index: index
            });
          },
          // 显示图片
          handleMouseenter: function (event, index) {
            if (!runtimeParam.showGoodsImg) {
              runtimeParam.showGoodsImg = $('#showGoodsImg');
            }
            var goods = newBillVm.chooseGoods[index];
            tools.throttle(runtimeParam.timeObj, function () {
              // 需要查询物品的地址信息 todo
              api.getImages({
                  className: 'ImageManager',
                  method: 'getImages',
                  imgType: '6',
                  goodsType: 1,
                  folder: goods.GoodsCode
                })
                .then(function (data) {
                  if (data.issuccess === 0) {
                    var result = JSON.parse(data.result);
                    if (result.length > 0) {
                      //tools.showImg(event, result[0], runtimeParam)();
                      tools.showImgDialog(result)();
                    }
                  }
                })
            });
          },
          // 隐藏图片
          handleMouseout: function (event, index) {
            tools.throttle(runtimeParam.timeObj, function () {
              runtimeParam.showGoodsImg.hide();
            });
          },
          // 查询账户信息
          queryAccount: function () {
            new AccountQuery().init({
              deptAccountID: runtimeParam.InDeptAccountID,
              goodsBookID: runtimeParam.Openparm.GoodsBook
            });
          },
          // 打印领用单
          billPrint: function () {
            window.open('print#!/ly/' + runtimeParam.Openparm.GoodsBook + '/' + runtimeParam.bill.BillSNf)
          },
          // enter 可以跳转到下一个输入框
          handlerEnter: function (event) {
            handlerEnter(event);
          }
        }
      };
      // enter 可以跳转到下一个输入框
      function handlerEnter(event) {
        var $input = $('.input-enter');
        $input.each(function (index, input) {
          if (input === event.target) {
            // 判断下个input是否存在
            if ($input[index + 1]) {
              $input[index + 1].focus();
            } else {
              // 判断是否选择物品 还是普通的输入框
              // 判断 单据类型
              if (runtimeParam.BillType !== 'dh' && runtimeParam.BillType !== 'jy') {
                if ($input[index - 2].classList.contains('input-goods')) {
                  $input[index - 1].focus();
                } else {
                  $input[index - 2].focus();
                }
              } else {
                $input[index - 1].focus();
              }
            }
          }
        });
      }

      // 根据单据类型来获取 需要保存的 单据modelsaveBill
      function saveBillByBillType(runtimeParam, newBillVm) {
        runtimeParam.refreshBillListTable = true; // 进行保存操作 表明要刷新列表
        switch (runtimeParam.BillType) {
          case 'ly':
            GoodsToDept(newBillVm.chooseGoods, newBillVm.InDeptAccountID); // 如果是领用单 检查物品能否被该科室领用
            break;
          case 'zy':
          case 'jh':
            batchDialog.init({
              api: api,
              Openparm: runtimeParam.Openparm,
              goodsInfo: JSON.parse(JSON.stringify(newBillVm.chooseGoods.$model)),
              InputDepAccountID: newBillVm.InputDepAccountID,
              OutDeptAccountID: newBillVm.OutDeptAccountID,
              BillStatus: runtimeParam.BillStatus,
              InputTransferBillError: function () {
                newBillVm.canSave = true;
              },
              InputTransferBill: InputTransferBill //保存方法
            });
            break;
          case 'dh':
            savePackageTransBill(newBillVm.chooseGoods, newBillVm, runtimeParam.isProviderDept);
            break;
          case 'jy':
            saveBill(true, newBillVm.chooseGoods.length, newBillVm.chooseGoods, false);
            break;
          case 'qxxd':
            saveBill(true, newBillVm.chooseGoods.length, newBillVm.chooseGoods, false);
            break;
          case 'sq':
            saveBill(true, newBillVm.chooseGoods.length, newBillVm.chooseGoods, false);
            break;
        }
      }

      // 发送 和 作废操作
      function sendAndNullifyBill(bill, obj) {
          
    	  var param = {
          className: obj.className,
          method: obj.sendMethod,
          billSN: bill.BillSN || bill.lsh,
          userID: runtimeParam.user.Ygid
        };
        api.sendDrawBill(param).then(function (jsonResult) {
        	 
          if (jsonResult.issuccess !== 0) {
        	  
            return Promise.reject('获取信息失败');
          }
          runtimeParam.BillStatus = 'view';
          newBillVm.BillStatus = 'view';
          tools.alterInfo('发送成功');
          // 提交申请后 跳转到 列表页面 不再需要 获取信息
          setTimeout(function () {
            newBillVm.back();
          }, 200);
          // getBill(obj, true);
        })['catch'](function (ex) {
          tools.handleError(ex);
        });
      }
      //获取科室余额
      function getDepBalance(cb){
    	  console.log(runtimeParam)
    	  api.getAccountBalance({
    	      className: 'ChargeBillManager',
    	      method: 'GetAccountBalance',
    	      deptAccountID: runtimeParam.CurrentDeptAccount.DeptAccountID
    	    }).then(function (jsonResult) {
    	    	if(jsonResult.issuccess == 0){
    	    		var balance= Number(JSON.parse(jsonResult.result).Balance);
    	    		cb(balance);
    	    	}else Promise.reject('获取信息失败');
    	    	
    	  })
      }
       
      //获取科室超额额度
      function getDepLimit(cb){
    	  var condition ={"ColumnName":"a.DeptAccountID","FullString":null,"Oper":"Equal","Value":runtimeParam.CurrentDeptAccount.DeptAccountID,"Type":"AnsiString"} 
    	  api.getAccountLimit({ className: 'ChargeBillManager',
    	      method: 'GetAccountLimit',
    		  condition:JSON.stringify(condition)
    	    }).then(function (jsonResult) {
    	    	if(jsonResult.issuccess == 0){
    	    		var aboveNorm = 0;
    	    		if(!!JSON.parse(jsonResult.result)[0]){
    	    			aboveNorm = Number(JSON.parse(jsonResult.result)[0].Line);
    	    		}
    	    		cb(aboveNorm);
    	    	}else Promise.reject('获取信息失败');
    	    	
    	  })
      }
      // 保存前检查 申请数量
      function checkApplyCount() {
    	        if (runtimeParam.BillType !== 'jh' && newBillVm.InDeptAccountID === runtimeParam.OutDeptAccount.DeptAccountID) {
    	          tools.alterError("不能转移到供应科室，请使用缴回流程");
    	          return false;
    	        }
    	        if (newBillVm.chooseGoods.length <= 0) {
    	          tools.alterError("请选择物品！");
    	          return false;
    	        }
    	        if (!newBillVm.InDeptAccountID && runtimeParam.BillType !== 'qxxd') {
    	          tools.alterError("请选择领用科室！");
    	          return false;
    	        }
    	        if (!newBillVm.OutDeptAccountID && runtimeParam.BillType !== 'qxxd') {
    	          tools.alterError("请选择出库科室！");
    	          return false;
    	        }
    	        if (newBillVm.InDeptAccountID === newBillVm.OutDeptAccountID && runtimeParam.BillType !== 'qxxd') {
    	          tools.alterError("入库科室和出库科室不能一样！");
    	          return false;
    	        }
    	        // 循环整个数组 判断是否有 申请数大于库存
    	        for (var i = 0; i < newBillVm.chooseGoods.length; i++) {
    	          var data = newBillVm.chooseGoods[i];
    	        //  console.log(data.$model.consultMoney);
    	          if (parseInt(data.ApplyNum) <= 0) {
    	            tools.alterError(data.GoodsName + "的申请数不正确，请确认!");
    	            return false;
    	          }
    	          // 调回单 借用单 需要判断 基数
    	          if (runtimeParam.BillType !== 'dh' && runtimeParam.BillType !== 'jy' && runtimeParam.BillType !== 'qxxd' && runtimeParam.BillType !== 'sq') {
    	            if (parseInt(data.ApplyNum) > parseInt(data.GoodsCount)) {
    	              tools.alterError(data.GoodsName + "的库存数不足，请确认!");
    	              return false;
    	            }
    	          }
    	          
    	        }
    	        return true;
      }

      // 领用单 查看能否被当前科室领用
      function GoodsToDept(goods, inputDeptAccountID, isSend) {
        var requestCount = 0; // 请求次数 当请求次数 和 商品的数量相同的时候 可以进行下步操作
        var canBeDrawed = false; // 是否能被领用

        goods.forEach(function (data) {
          if (!canBeDrawed) { // 当一个物品不能被领用的时候 就不需要在 继续检测
            api.selectGoodsToDept({
              className: 'GoodsManager',
              method: 'SelectGoodsToDept',
              goodsID: data.GoodsID
            }).then(function (jsonResult) {

              requestCount++;
              var depts = JSON.parse(jsonResult.result);

              // 供应室不需要检查可是是否可领
              if (depts.length === 0 || runtimeParam.isGYKS) {
                canBeDrawed = true;
              } else {
                for (var i = 0; i < depts.length; i++) {
                  if (depts[i].DeptAccountID === inputDeptAccountID) {
                    canBeDrawed = true;
                    break;
                  } else {
                    canBeDrawed = false;
                  }
                }
              }

              if (!canBeDrawed) {
                return Promise.reject('你输入的物品<' + data.GoodsName + '>不能被' +
                  newBillVm.InDeptName + "所领用！");
              }
              saveBill(canBeDrawed, requestCount, goods, isSend);
            })['catch'](function (ex) {
              newBillVm.canSave = true;
              tools.handleError(ex);
            });
          }
        });
      }

      // 转移单 and 缴回单 保存
      function InputTransferBill(chooseGoods, batchSelections, isSend) {
        var drawBill = buildBillInfo.getDrawBill(chooseGoods, newBillVm, runtimeParam.Openparm, runtimeParam);
        // 根据当前的单据状态决定是新增或更新
        var obj = getApiConfig.buildNewBillRequestParam(newBillVm.isGYKS, isSend, runtimeParam.BillStatus, runtimeParam.BillType);
        handleSaveApi(obj, drawBill, batchSelections, isSend);
      }

      // 保存 调换单
      function savePackageTransBill(chooseGoods, newBillVm, isSend) {
        // 先判断 是否超出基数
        var goods = JSON.parse(JSON.stringify(chooseGoods.$model));
        var canBeDrawed = true,
          requestCount = 0;
        goods.forEach(function (good) {
          var condition1 = new Condition("bc.DeptAccountID", null, "Equal", newBillVm.InDeptAccountID, "String");
          var condition2 = new Condition("bc.PackageID", null, "Equal", good.GoodsID, "String");
          var conditions = new Conditions([condition1, condition2], 'AND');
          var param = Object.assign({}, param, {
            className: 'PackageBaseCountManager',
            method: 'GetPackageBaseCounts',
            condition: JSON.stringify(conditions)
          });
          api.getGoodsBatchStatus(param).then(function (jsonResult) {
        	 
            if (jsonResult.issuccess !== 0) {
              return Promise.reject('获取信息失败');
            }
            requestCount++;
            var result = JSON.parse(jsonResult.result);
            var baseCount;
            if (Array.isArray(result) && result.length > 0) {
              baseCount = result[0].Counts;
            } else {
              baseCount = 0;
            }
            if (!(baseCount === 0) && !(baseCount > 0 && parseInt(good.ApplyNum) <= baseCount)) {
              tools.alterError('科室' + newBillVm.InDeptName + "的包" + good.GoodsName + '的基数为' + baseCount + '，申请数不能大于此基数');
              canBeDrawed = false;
            }
            // dh单 保存
            saveBill(canBeDrawed, requestCount, newBillVm.chooseGoods, isSend);
          })['catch'](function (ex) {
            newBillVm.canSave = true;
            tools.handleError(ex);
          });
        });
      }

      // 保存操作
      function saveBill(canBeDrawed, requestCount, goods, isSend) {
        // 判断是否可以进行下一步操作
        if (canBeDrawed && requestCount === goods.length) {
          var drawBill = buildBillInfo.getDrawBill(goods, newBillVm, runtimeParam.Openparm, runtimeParam);
          // 根据当前的单据状态决定是新增或更新
          var obj = getApiConfig.buildNewBillRequestParam(newBillVm.isGYKS, isSend, runtimeParam.BillStatus, runtimeParam.BillType);
          handleSaveApi(obj, drawBill, '[]', isSend);
        }
      }

      // 处理保存
      function handleSaveApi(obj, drawBill, batchSelections, isSend) {
        var param = { // 保存 and 更新
          className: obj.className,
          method: obj.method,
          drawBill: JSON.stringify(drawBill),
          userID: runtimeParam.user.Ygid,
          batchSelections: JSON.stringify(batchSelections)
        };
        // 根据单据的不同需要设定 不同的请求参数
        switch (runtimeParam.BillType) {
          case 'zy':
            delete param.drawBill;
            if (isSend) {
              param = Object.assign({}, param, {
                bill: JSON.stringify(drawBill)
              });
            } else {
              param = Object.assign({}, param, {
                transBill: JSON.stringify(drawBill)
              });
            }
            break;
          case 'jh':
            delete param.drawBill;
            param = Object.assign({}, param, {
              drawBackBill: JSON.stringify(drawBill)
            });
            break;
          case 'dh':
            delete param.drawBill;
            param = Object.assign({}, param, {
              transBill: JSON.stringify(drawBill)
            });
            break;
          case 'qxxd':
            delete param.drawBill;
            param = Object.assign({}, param, {
              disinfectBill: JSON.stringify(drawBill)
            });
            break;
          case 'sq':
            delete param.drawBill;
            param = Object.assign({}, param, {
              head: JSON.stringify(drawBill.Head),
              details: JSON.stringify(drawBill.Details)
            });
            break;
        }
        
        api.inputDrawBill(param).then(function (jsonResult) {
          if (jsonResult.issuccess == 1) {
            return Promise.reject(jsonResult.message);
          }

          if (runtimeParam.BillStatus === 'new') {
            newBillVm.bill.BillSN = jsonResult.result;
            newBillVm.bill.lsh = jsonResult.result;
          }
          newBillVm.StatusStr = runtimeParam.statusStr[obj.status]; // 状态
          tools.alterInfo(obj.info);
          // 调回单 发送 如果是供应科室 直接发送
          if (isSend && (runtimeParam.BillType === 'dh' || runtimeParam.BillType === 'jy')) {
            sendAndNullifyBill({
              BillSN: newBillVm.bill.BillSN
            }, obj);
          } else {
            getBill(obj);
          }
        })['catch'](function (ex) {
          newBillVm.canSave = true;
          tools.handleError(ex);
        });
      }

      // 查找单据
      function getBill(obj, isSend) {
        // 申请单需要 加上 condition
        api.getBill({
          className: obj.getBillClassName,
          method: obj.getBillMethod,
          billSN: newBillVm.bill.BillSN || newBillVm.bill.lsh,
          condition: JSON.stringify(new Condition("a.lsh", null, 'Equal', (newBillVm.bill.BillSN || newBillVm.bill.lsh), 'String'))
        }).then(function (jsonResult) {

          if (jsonResult.issuccess === 0 && jsonResult.result !== 'null') {
            // 申请单是个数组
            var result;
            if (runtimeParam.BillType !== 'sq') {
              result = JSON.parse(jsonResult.result);
              runtimeParam.bill = result.Head;
            } else {
              result = JSON.parse(jsonResult.result)[0];
              runtimeParam.bill = result;
            }
            // 设置单据的信息 防止出现为空 或者 undefined
            Object.keys(runtimeParam.bill).forEach(function (key) {
              if (runtimeParam.bill[key]) {
                runtimeParam.bill[key] = runtimeParam.bill[key];
              } else {
                runtimeParam.bill[key] = '';
              }
            });
            // 申请单的状态需要改变
            runtimeParam.bill.strStatus = runtimeParam.statusStr[runtimeParam.bill.StatusStr];
            if (runtimeParam.BillType === 'sq') {
              runtimeParam.bill.strStatus = runtimeParam.bill.zt === '1' ? '申请' : '发送';
            }
            newBillVm.bill = runtimeParam.bill;
            // 借用和调换 需要设置 单据类型
            if (newBillVm.BillType === 'dh' || newBillVm.BillType === 'jy') {
              newBillVm.bill.BillTypeStr = runtimeParam.bill.BillTypeStr === 'dh' ? '调换单' : '借用单';
            }
            // 修改可以保存的单据状态
            newBillVm.isChange = false;
            newBillVm.canSave = true;

            if (runtimeParam.BillStatus === 'new') {
              runtimeParam.BillStatus = 'change';
              newBillVm.BillStatus = 'change';
            } else if (isSend) {
              runtimeParam.BillStatus = 'view';
              newBillVm.BillStatus = 'view';
            }

            // 调换单 不能修改物品信息
            // 此处是更新所有的单据信息
            // 申请单需要重新查询 才能更新详情
            if (runtimeParam.BillType !== 'sq') {
              newBillVm.chooseGoods.forEach(function (item, index) {
                Object.keys(result.Details[index]).forEach(function (key) {
                  if (result.Details[index][key] !== null) {
                    item[key] = result.Details[index][key];
                  }
                });
                // 更新 申请参考金额
                item.consultMoney = parseInt(item.ApplyNum) * item.RefPrice
              })
            } else {
              newBillVm.chooseGoods.forEach(function (item) {
                item.consultMoney = parseInt(item.ApplyNum) * item.Price
              })
            }
          }
        })['catch'](function (ex) {
          tools.handleError(ex);
        })
      }

      // 初始化 单据信息
      function initVm(newBillVm, bill, statusStr, isChange) {

        if (runtimeParam.BillType === 'jh' && runtimeParam.BillStatus === 'new') {
          var oldBill = Object.assign({}, bill);
          bill.InDeptName = oldBill.OutDeptName;
          bill.InDeptAccountID = oldBill.OutDeptAccountID;
          bill.InDeptCode = oldBill.OutDeptCode;
          bill.OutDeptName = oldBill.InDeptName;
          bill.OutDeptAccountID = oldBill.InDeptAccountID;
          bill.OutDeptCode = oldBill.InDeptCode;
        }

        // 器械消毒单 不需要这些科室选项
        if (runtimeParam.BillType !== 'qxxd') {
          // 不同的科室 可能每个名称的字段不同
          newBillVm.InDeptName = bill.InDeptName ? bill.InDeptName : bill.ApplyDeptName; //入库科室
          newBillVm.InDeptAccountID = bill.ApplyDeptAccountID || bill.InDeptAccountID; //入库科室
          newBillVm.InDeptAccountCode = bill.ApplyDeptID || bill.InDeptCode; //入库科室
          newBillVm.OutDeptName = bill.OutDeptName ? bill.OutDeptName : bill.OutDeptAccountName; //出库科室
          newBillVm.OutDeptAccountID = bill.OutDeptAccountID || ''; //出库科室
          newBillVm.OutDeptAccountCode = bill.OutDeptID || bill.OutDeptCode; //出库科室
        }

        newBillVm.isChange = isChange;
        newBillVm.InDeptName = newBillVm.InDeptName ? newBillVm.InDeptName.trim() : '';
        newBillVm.OutDeptName = newBillVm.OutDeptName ? newBillVm.OutDeptName.trim() : '';
      }

      // 获取请求参数
      function getRequestParam(newBillVm, bill) {
        var className = 'MoveBillQueryManager',
          method = 'GetBillDetailsBySN';
        var getCountClassName = 'StoreBatchManager',
          getCountMethod = 'GetGoodsBatchStatus';

        if (newBillVm.isGYKS) {
          method = 'GetBill';
          className = 'GyzxDrawBillManager';
          getCountClassName = 'PackageStoreManager';
          getCountMethod = 'GetFormalCurrentCount';
          switch (runtimeParam.BillType) {
            case 'dh':
            case 'jy':
              className = 'PackTransBillQueryManager';
              method = 'GetTransBill';
              break;
            case 'qxxd':
              className = 'DisinfectBillManager';
              method = 'GetDisinfectBill';
              break;
            case 'sq':
              className = 'DisinfectBillManager';
              method = 'GetDisinfectBill';
              break;
          }
        }

        var requestParam;
        // 申请单需要特殊处理
        if (runtimeParam.BillType === 'sq') {
          requestParam = {
            className: 'SqhzdMxManager',
            method: 'GetSqhzdMx',
            condition: JSON.stringify(new Condition("a.lsh", null, 'Equal', bill.BillSN, 'String'))
          };
        } else {
          requestParam = {
            className: className,
            method: method,
            billSN: bill.BillSN
          };
        }
        return {
          getCountClassName: getCountClassName,
          getCountMethod: getCountMethod,
          requestParam: requestParam
        };
      }

      // 获取单据的明细信息
      function getBilDetailInfo(newBillVm, bill) {
        var __ret = getRequestParam(newBillVm, bill);
        var getCountClassName = __ret.getCountClassName;
        var getCountMethod = __ret.getCountMethod;
        var requestParam = __ret.requestParam;

        // 获取流转单明细
        api.getBillDetailsBySN(requestParam)
          .then(function (jsonResult) {

            if (jsonResult.issuccess !== 0) {
              return Promise.reject("获取信息失败");
            }

            var result;
            if (newBillVm.isGYKS) {
              result = JSON.parse(jsonResult.result).Details;
            } else {
              result = JSON.parse(jsonResult.result);
            }

            // 计算 调换 借用 收污数 使用
            var CollectBills;
            if (runtimeParam.BillType === 'dh' || runtimeParam.BillType === 'jy') {
              CollectBills = JSON.parse(jsonResult.result).CollectBills;
            }
            result.forEach(function (data) {
              // todo 位数 显示 问题 需要使用 toFixed() 方法固定 位数
              data.consultMoney = data.RefPrice * parseInt(data.ApplyNum);
              data.Comment = data.Comment || '';
              if (runtimeParam.BillType === 'dh' || runtimeParam.BillType === 'jy') {
                data.ApplyNum = data.Counts;
                // 调换单的 收污数 修改
                if (CollectBills) {
                  CollectBills.forEach(function (item) {
                    if (item.Details) {
                      var collectItem = item.Details.filter(function (item) {
                        return item.PackageID === data.PackageID;
                      });
                      collectItem.forEach(function (collect) {
                        data.ToCollectNum += collect.Count;
                      })
                    }
                  });
                }
              } else if (runtimeParam.BillType === 'qxxd') {
                data.ApplyNum = data.ApplyCounts;
              }
            });
            newBillVm.chooseGoods.splice(0, newBillVm.chooseGoods.length);
            newBillVm.chooseGoods.pushArray(result);
            runtimeParam.billDetail = Object.assign({}, result);
            return result;

          }).then(function (result) {

            // 更新库存操作
            for (var i = 0; i < result.length; i++) {

              (function (i) {
                var param = {
                  className: getCountClassName,
                  method: getCountMethod,
                  goodsID: result[i].GoodsID,
                  deptAccountID: newBillVm.OutDeptAccountID
                };
                param = !newBillVm.isGYKS ? param : Object.assign({}, param, {
                  packageID: result[i].GoodsID
                });
                api.getGoodsBatchStatus(param).then(function (jsonResult) {
                	 
                  if (jsonResult.issuccess === 0) {
                    var newBill = Object.assign({}, JSON.parse(JSON.stringify(newBillVm.chooseGoods[i].$model)), {
                      GoodsCount: !newBillVm.isGYKS ? JSON.parse(jsonResult.result).GoodsCount : JSON.parse(jsonResult.result)
                    });
                    newBillVm.chooseGoods.set(i, newBill)
                  }
                })
              }(i));
            }
          })['catch'](function (ex) {
            tools.handleError(ex);
          });
      }

      // 获取单据信息
      function initBillInfo(bill, newBillVm, statusStr, isChange) {
        initVm(newBillVm, bill, statusStr, isChange);
        getBilDetailInfo(newBillVm, bill);
      }

      // 新建 单据
      function buildNewBill(statusStr, BillType) {
    	 
        // 转移和其他的也都不同
        var bill = {
          OutDeptName: BillType === "zy" ? runtimeParam.CurrentDeptAccount.Ksmc : runtimeParam.OutDeptAccount.Ksmc,
          OutDeptAccountID: BillType === "zy" ? runtimeParam.CurrentDeptAccount.DeptAccountID : runtimeParam.OutDeptAccount.DeptAccountID,
          OutDeptCode: BillType === "zy" ? runtimeParam.CurrentDeptAccount.Ksdm : runtimeParam.OutDeptAccount.Ksdm,
          InDeptName: BillType === "zy" ? '' : runtimeParam.CurrentDeptAccount.Ksmc,
          InDeptAccountID: BillType === "zy" ? '' : runtimeParam.CurrentDeptAccount.DeptAccountID,
          InDeptCode: BillType === "zy" ? '' : runtimeParam.CurrentDeptAccount.Ksdm
        };
        initVm(newBillVm, bill, statusStr, true);

        newBillVm.bill.InputUserName = runtimeParam.user.Xm;
        newBillVm.bill.DeptName = runtimeParam.CurrentDeptAccount.Ksmc;
        newBillVm.bill.Sqrmc = runtimeParam.user.Xm; // 申请单
        newBillVm.chooseGoods.splice(0, newBillVm.chooseGoods.length);
      }

      // 根据单据类型 设定 输入框状态
      function settingInputStatus(input, out) {
        newBillVm.InDeptNameDisabled = input;
        newBillVm.OutDeptNameDisabled = out;
      }

      // 根据单据类型 初始化 入库和出库科室是否可选
      var sureInputStatus = function (BillType, BillStatus) {
        var input, out;
        switch (BillType) {
          case 'ly':
            input = !runtimeParam.isProviderDept;
            out = runtimeParam.isProviderDept ? true : true;
            break;
          case 'zy':
            input = runtimeParam.isProviderDept ? false : false;
            out = !runtimeParam.isProviderDept;
            break;
          case 'jh':
            input = !runtimeParam.isProviderDept;
            out = runtimeParam.isProviderDept ? true : true;
            break;
          case 'dh':
            input = false;
            out = true;
            break;
          case 'jy':
            input = !runtimeParam.isProviderDept;
            out = true;
            break;
          default:
            input = true;
            out = true;
            break;
        }
        if (BillStatus === 'view') {
          input = true;
          out = true;
        }
        settingInputStatus(input, out);
      };

      // 初始化 表格内容 根据不同的单据类型类获取不同的表格
      function initGoodsTableContent(tableId, formId, BillStatus, BillType) {
        var table = $(tableId);
        var form = $(formId);
        table.html('');
        form.html('');
        switch (BillStatus) {
          case 'view':
            table.append(viewNewBillTable);
            if (BillType === 'dh' || BillType === 'jy') {
              form.append(packageBillForm);
            } else if (BillType === 'qxxd') {
              form.append(disinfectBillForm);
            } else if (BillType === 'sq') {
              form.append(applyBillForm);
            } else {
              form.append(comNewBillForm);
            }
            break;
          case 'new':
          case 'change':
            if (BillType === 'dh' || BillType === 'jy') {
              table.append(packageBillTable);
              form.append(packageBillForm);
            } else if (BillType === 'qxxd') {
              table.append(disinfectBillTable);
              form.append(disinfectBillForm);
            } else if (BillType === 'sq') {
              table.append(applyBillTable);
              form.append(applyBillForm);
            } else {
              table.append(comNewBillTable);
              form.append(comNewBillForm);
            }
            break;
        }
      }
      
      this.init = function ($main, param) {
    	  //阳光申请param
    	  //YsqlParam($main, param);
    	  
        runtimeParam = getRuntimeParam();
        runtimeParam = Object.assign(runtimeParam, param);

        $main.append(htmlTemp);
        initGoodsTableContent('#tdContent', '#billForm', runtimeParam.BillStatus, runtimeParam.BillType);
        newBillVm = tools.initAvalonVm(avalon, getVmOption(), ".new-bill");

        sureInputStatus(runtimeParam.BillType, runtimeParam.BillStatus); // 设定输入状态
        runtimeParam.CurrentDeptAccount = JSON.parse(localStorage.getItem('deptInfo'));
        runtimeParam.user = JSON.parse(localStorage.getItem('currentUser'));

        newBillVm.breadcrumb = param.breadcrumb; // 路径
        newBillVm.BillStatus = runtimeParam.BillStatus;
        newBillVm.BillType = runtimeParam.BillType;
        newBillVm.isGYKS = runtimeParam.isGYKS; // 是否是供应室

        // 防止输入框出现 undefined
        Object.keys(newBillVm.bill.$model).forEach(function (key) {
          if (param.bill[key]) {
            newBillVm.bill[key] = param.bill[key];
          } else {
            newBillVm.bill[key] = '';
          }
        });

        // 调换单和借用单需要出现 单据类型
        if (newBillVm.BillType === 'dh' || newBillVm.BillType === 'jy') {
          newBillVm.bill.BillTypeStr = newBillVm.BillType === 'dh' ? '调换单' : '借用单';
        }

        newBillVm.inputGoodsName = '';
        newBillVm.columnNames.pushArray(getVmConfig.getNewBillTableColumnNames(newBillVm.isGYKS, runtimeParam.BillType)); // 获取表格列名
        newBillVm.columnValueNames.pushArray(getVmConfig.getNewBillTableColumnValueNames(newBillVm.isGYKS, runtimeParam.BillType)); // 获取表格列名

        // 根据不同的 状态来 初始化 表单和表格
        // 新建
        if (runtimeParam.BillStatus === 'new') {
          buildNewBill(runtimeParam.statusStr, runtimeParam.BillType);
        }
        // 查看
        else if (runtimeParam.BillStatus === 'view' || runtimeParam.BillStatus === 'change') {
          runtimeParam.bill = param.bill;
          initBillInfo(runtimeParam.bill, newBillVm, runtimeParam.statusStr, false);
        }
        // 生成 显示图片的 div
        if (!document.querySelector("#showGoodsImg")) {
          $(document.body).append('<div id="showGoodsImg" class="showGoodsImg"><img src="" alt=""/></div>');
        }
        // 需要监听
        tools.bindDestroyMethod(self.destroy);
      };

      this.destroy = function () {
        runtimeParam = null;
        newBillVm = null;
        if (document.querySelector("#showGoodsImg")) {
          document.body.removeChild(document.querySelector('#showGoodsImg'))
        }
        tools.destroy(getVmOption());
      };
      
      function YsqlParam($main, param){
    	  ygsq$main=$main;
    	  ygsqParam=param;
    	  //ygsqParam.breadcrumb="阳光采购申请单-申请单管理";
      }
    };
  });